package com.jiazhong.mingxing.project.bookstore.front.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiazhong.mingxing.project.bookstore.commons.bean.OrderItem;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Stock;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.OrderItemMapper;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.StockMapper;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "ab125", topic = "order", selectorExpression = "success", messageModel = MessageModel.BROADCASTING)
public class UpdateStockListener implements RocketMQListener<String> {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Override
    public void onMessage(String s) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", s);
        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);
        for (OrderItem orderItem : orderItems) {
            // 图书ID
            String bookId = orderItem.getBookId();
            // 要购买的数量
            Integer number = orderItem.getNumber();
            // 查询图书在库存中的信息
            QueryWrapper<Stock> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("book_id", bookId);
            Stock stock = stockMapper.selectOne(wrapper1);
            stock.setNumber(stock.getNumber() - number);
            stockMapper.updateById(stock);
        }

    }
}
